<?php

namespace app\admin\model;

use think\Model;

class UserList extends Model
{
    protected $autoWriteTimestamp = true;

    protected $pk = 'user_id';

    public static function getList()
    {
        $where = [];
        $limit = input('get.limit');
        $page = input('get.page');
        if (input('get.user_name')) $where[] = ['user_name', 'like', "%" . input('get.user_name') . "%"];
        if (input('get.user_mobile')) $where[] = ['user_mobile', 'like', "%" . input('get.user_mobile') . "%"];
        $list = self::order('user_id', 'desc')
            ->where($where)
            ->paginate($limit);
        foreach ($list as $k => $v) {
            $list[$k]['user_sex'] = !$v['user_sex'] ? '未知' : ($v['user_sex'] == 1 ? '男' : '女');
            $list[$k]['user_mobile'] = $v['user_mobile'] ?: '未填写';
            $list[$k]['user_age'] = $v['user_birth'] ? getAgeByBirthday(date('Y-m-d', $v['user_birth'])) . '岁' : '未填写';
            $list[$k]['user_birth'] = $v['user_birth'] ? date('Y年m月d日', $v['user_birth']) : '未填写';
        }
        return ['code' => 0, 'data' => $list->items(), 'extend' => ['count' => $list->total(), 'limit' => $limit, 'page' => $page]];
    }

    public static function getSearchUser()
    {
        $search = input('get.keyword');
        $page = input('get.page');
        $limit = input('get.pageSize');
        $userId = input('get.userId') ?? 0;
        $list = self::where('user_name|user_mobile', 'like', "%{$search}%")
            ->page($page, $limit)
            ->order('user_id', 'desc')
            ->field('user_id,user_name')
            ->select()
            ->toArray();
        $data = array_map(function ($item) use ($userId) {
            return [
                'name' => $item['user_name'],
                'value' => $item['user_id'],
                'selected' => $item['user_id'] == $userId
            ];
        }, $list);
        return ['code' => 0, 'data' => ['totalCount' => self::count(), 'list' => $data]];
    }
}